﻿using Framework.Domain.Model;
using Framework.Infrastructure;
using Framework.Infrastructure.Cache.Redis;
using Framework.Infrastructure.RabbitMQ;
using Framework.MVC.Infrastructure.ActionResultExt;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Framework.MVC.Infrastructure
{
    /// <summary>
    /// 控制器基类
    /// </summary>
    public class BaseController : Controller
    {
        protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            return new JsonNetResult
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = contentEncoding,
                JsonRequestBehavior = behavior
            };
        }

        /// <summary>
        /// 接口访问次数统计
        /// 继承BaseController的Controller下的Action才会统计访问次数
        /// 此OnActionExecuting方法在【授权过滤器】和【模型绑定】之后运行，如果这俩返回错误或者报错，那么该接口的访问次数不会被统计
        /// 过滤器执行顺序：http://www.cnblogs.com/Showshare/p/exception-handle-with-mvcfilter.html
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            SYS_ApiVisitLog visitLog = new SYS_ApiVisitLog();
            visitLog.Api = Request.RequestContext.RouteData.Values["controller"].ToString() + "/" + filterContext.ActionDescriptor.ActionName;
            visitLog.VisitTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));

            //RabbitMQ消息发布
            RabbitPublisher.Publish(new RabbitModel_Base { ModelType = RabbitModel_Enum.ApiVisitLog, ApiVisitLog = visitLog });
        }

        /// <summary>
        /// 根据Token获取对象（后台）
        /// </summary>
        /// <param name="token">token</param>
        /// <returns></returns>
        public static BKTokenModel GetBKTokenModelByToken(string token)
        {
            if (string.IsNullOrWhiteSpace(token) || token.Split('.').Length != 3)
                return null;
            var jsonStr = Common.JWTDecodeBK(token);
            return JsonConvert.DeserializeObject<BKTokenModel>(jsonStr);
        }

        /// <summary>
        /// 根据Token获取对象（手机端）
        /// </summary>
        /// <param name="token">token</param>
        /// <returns></returns>
        public static PhoneTokenModel GetPhoneTokenModelByToken(string token)
        {
            if (string.IsNullOrWhiteSpace(token) || token.Split('.').Length != 3)
                return null;
            var jsonStr = Common.JWTDecodePhone(token);
            return JsonConvert.DeserializeObject<PhoneTokenModel>(jsonStr);
        }

    }
}